package com.xauto.pioneer.appuser.activity.mine.receipt;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.activity.common.PayUtil;
import com.xauto.pioneer.appuser.activity.common.PromptResultActivity;
import com.xauto.pioneer.appuser.adapter.PaymentAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.Payment;
import com.xauto.pioneer.appuser.model.SubmitReceiptData;
import com.xauto.pioneer.appuser.util.ListViewUtil;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.view.TopBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static com.xauto.pioneer.appuser.R.id.account_balance_text;

/**申请发票信息确认
 * Created by Administrator on 2018/5/29.
 */

public class ApplyReceiptInfoActivity extends BaseActivity {

    @Bind(R.id.applyreceiptinfo_listPayment)
    ListView applyreceiptinfo_listPayment;
    @Bind(R.id.topBar_applyreceiptinfo)
    TopBar topBar_applyreceiptinfo;
    @Bind(R.id.tv_receiptinfo_companyname)
    TextView tv_receiptinfo_companyname;
    @Bind(R.id.tv_receiptinfo_num)
    TextView tv_receiptinfo_num;
    @Bind(R.id.tv_receiptinfo_total)
    TextView tv_receiptinfo_total;
    @Bind(R.id.tv_receiptinfo_mailingcost)
    TextView tv_receiptinfo_mailingcost;
    @Bind(account_balance_text)
    TextView accountBalanceText;
    @Bind(R.id.applyreceiptinfo_tvPaySubmit)
    TextView applyreceiptinfo_tvPaySubmit;
    @Bind(R.id.cb_balance_select)
    CheckBox cb_balance_select;
    /** 支付方式适配器*/
    private PaymentAdapter paymentAdapter;
    //支付方式code
    String payment_code = "app-alipay";
    //使用账户余额(1-是/0-否) 默认为否
    String is_use_balance_amount = "0";
    /**申请开票订单ID*/
    String receiptOrderId;
    @Override
    protected int getContentView() {
        return R.layout.ac_applyreceiptinfo;
    }

    @Override
    protected void initView() {
        //注册EventBus
        EventBus.getDefault().register(this);
        topBar_applyreceiptinfo.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar_applyreceiptinfo.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
//        topBar_applyreceiptinfo.setImage(TopBar.LEFT_IMAGE, R.mipmap.ic_common_left);
        topBar_applyreceiptinfo.setText(TopBar.TITLE, "申请开票信息确认");
        topBar_applyreceiptinfo.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        cb_balance_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkoutForReceipt(payment_code,is_use_balance_amount);
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent  = getIntent();
        try {
            JSONObject jsonObject = new JSONObject(intent.getStringExtra("entity"));
            SubmitReceiptData data = new SubmitReceiptData().parse(jsonObject);
            tv_receiptinfo_companyname.setText("公司名称："+data.receiptInfo.receipt_name);
            tv_receiptinfo_num.setText("纳税人识别号："+data.receiptInfo.receipt_num);
            tv_receiptinfo_total.setText("开票金额："+data.receiptInfo.receipt_total);
            tv_receiptinfo_mailingcost.setText(data.mailing_cost+"元");
            receiptOrderId = data.receiptInfo.receipt_order_id;
            accountBalanceText.setText("账户余额:"+data.memberAccount.balance_amount_format);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        paymentAdapter = new PaymentAdapter(this, R.layout.item_payment);
        applyreceiptinfo_listPayment.setAdapter(paymentAdapter);
        applyreceiptinfo_listPayment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(!paymentAdapter.getDataList().get(position).isChoose) {
                    for (int i = 0; i < paymentAdapter.getDataList().size(); i++) {
                        paymentAdapter.getDataList().get(i).isChoose = false;
                    }
                    paymentAdapter.getDataList().get(position).isChoose = true;
                    paymentAdapter.notifyDataSetChanged();
                    payment_code = paymentAdapter.getDataList().get(position).getPayment_code();
                }
            }
        });
        showOrderCostData();
    }
    @OnClick({R.id.applyreceiptinfo_tvPaySubmit})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.applyreceiptinfo_tvPaySubmit:
                if(cb_balance_select.isChecked()){          //判断checkbox状态设置是否用余额
                    is_use_balance_amount = "1";
                }else {
                    is_use_balance_amount="0";
                }
//                checkoutForReceipt(payment_code,is_use_balance_amount);
                submitReceiptOrder();
                break;

        }
    }
    /**
     * 显示相关数据
     */
    private void showOrderCostData(){
        List<Payment> payments = new Payment().getPaymentListForOnLine(mContext);
        paymentAdapter.getDataList().addAll(payments);
        paymentAdapter.notifyDataSetChanged();
        ListViewUtil.setListViewHeightBasedOnChildren(applyreceiptinfo_listPayment);
    }
    /**
     * 结算
     */
    private void checkoutForReceipt(String payment_code,String is_use_balance_amount){
        new LHttpLib().checkoutForReceipt(mContext,memberId,payment_code,is_use_balance_amount,new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                Log.e("tag",jsonStatus.data.toString());
            }
        });
    }
    /**
     * 提交结算
     */
    private void submitReceiptOrder(){
        new LHttpLib().submitReceiptOrder(mContext,memberId,receiptOrderId,
                payment_code,is_use_balance_amount,new BaseLHttpHandler(mContext,true,true){
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        Log.e("tag",jsonStatus.data.toString());
                        String payment_order_param = jsonStatus.data.optString("payment_order_param");
                        String payment_order_url = jsonStatus.data.optString("payment_order_url");
                        //返回支付参数为空，则默认认为支付成
                        if (StringUtils.isEmpty(payment_order_param)){
                            rechargeSuccess();
                        }else {
                            new PayUtil(ApplyReceiptInfoActivity.this, payment_order_param,payment_code);
                        }
                    }
                });
    }
    /**
     * 订单支付成功
     */
    private void  rechargeSuccess(){
//        prompt("订单支付成功");
        //传递到OrderActivity || FoundCarActivity界面用于刷新列表数据
        EventBus.getDefault().post("success");
        finish();
        PromptResultActivity.startAction(ApplyReceiptInfoActivity.this,"成功","支付成功\n欢迎你下次继续使用", Constants.PROMPT_RESULT_SUCCESS);
    }

    /**
     * 接受支付成功的通知信息
     * @param paymentCode
     */
    public void onEventMainThread(String paymentCode){
        switch (paymentCode){
            //支付宝支付成功
            case Constants.PAY_TYPE_ALIPAY:
                rechargeSuccess();
                break;
            //微信支付成功
            case Constants.PAY_TYPE_WECHAT:
                rechargeSuccess();
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册EventBus
        EventBus.getDefault().unregister(this);
    }
}

